﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using RGBFinder.Resources;
using Microsoft.Phone.Tasks;
using System.Threading;
using System.Xml.Serialization;

using Microsoft.Advertising.Mobile.UI;

namespace RGBFinder
{
    public enum SetType
    {
        None,
        Red,
        Green,
        Blue
    }
    public enum GameDifficulty
    {
        Easy,
        Normal,
        Hard,
        Reverse,
        Alpha
    }

    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        
        public static string MTGScore_ID = "5b8e1d81-a866-e011-81d2-78e7d1fa76f8";
        public static string MTGCards_ID = "8e788bb0-9067-e011-81d2-78e7d1fa76f8";
        public static string MTGHelps_ID = "8ee0b8fe-8e67-e011-81d2-78e7d1fa76f8";
        public static string MTGDice_ID = "db4da84e-5768-e011-81d2-78e7d1fa76f8";
        public static string InformaTreni_ID = "75c4de83-134c-e011-854c-00237de2db9e";
        public static string ChainingExplosion_ID = "6f6e33a9-6558-e011-854c-00237de2db9e";
        public static string EbookReader_ID = "c7ded5b0-17d6-df11-a844-00237de2db9e";
        public static string TapSequence_ID = "3cf38972-3573-e011-81d2-78e7d1fa76f8";
        public static string BoardGameSuite_ID = "e8201966-ff70-e011-81d2-78e7d1fa76f8";
        public static string Enigma_ID = "ad6556b4-bf71-e011-81d2-78e7d1fa76f8";
        public static string IdeoPuzzle_ID = "f7ffd022-63dc-df11-a844-00237de2db9e";
        public static string TriangleShooter_ID = "a08a8336-3cfe-df11-9264-00237de2db9e";
        public static string SapceBattle_ID = "0ee14cb1-cad9-df11-a844-00237de2db9e";

        public static string Global_Ranking = "";
        
        public static bool showScores = false;
        
        public MainPage()
        {
            InitializeComponent();

            Microsoft.Advertising.Mobile.UI.AdControl.TestMode = false;
           

            DataContext = App.ViewModel;
            Ads_List.ItemsSource = App.ViewModel.Ads;
            Scores_List.ItemsSource = App.ViewModel.Scores;
            GameType_List.ItemsSource = App.ViewModel.GameTypes;

            ApplicationBar.Buttons.Clear();
            ApplicationBarIconButton credits = new ApplicationBarIconButton() { Text = Strings.Credits, IsEnabled = true };
            ApplicationBarIconButton clearScore = new ApplicationBarIconButton() { Text = Strings.ClearScore, IsEnabled = true };
            if (App.CurrentTheme == App.Theme.Dark)
            {
                credits.IconUri = new Uri("\\Images\\dark\\appbar.questionmark.rest.png", UriKind.Relative);
                clearScore.IconUri = new Uri("\\Images\\dark\\delete.png", UriKind.Relative);
            }
            else
            {
                credits.IconUri = new Uri("\\Images\\light\\appbar.questionmark.rest.png", UriKind.Relative);
                clearScore.IconUri = new Uri("\\Images\\light\\delete.png", UriKind.Relative);
            }
            credits.Click += OpenCredits_Button_Click;
            clearScore.Click += ClearScore_Button_Click;
            ApplicationBar.Buttons.Add(credits);
            ApplicationBar.Buttons.Add(clearScore);
            //if (!App.isTrial())
            //{
            //    //AdControlGrid.Visibility = System.Windows.Visibility.Collapsed;
            //    //AdControl.Visibility = System.Windows.Visibility.Collapsed;

            //    Ads1_Button.Visibility = System.Windows.Visibility.Collapsed;
            //    Grid.SetRowSpan(Results_List, 2);
            //}

            //string s = Scoreboard.getID();

            try
            {
                var occ = Scoreboard.LoadUtilizations() + 1;
                new Thread(new ThreadStart(() =>
                    {
                        Scoreboard.getHTML(Scoreboard.GetUtilizationUrl(occ, App.isTrial()), 
                            (s) =>
                            {
                                Scoreboard.DeleteUtilizations();
                            },
                            () =>
                            {
                                Scoreboard.SaveUtilizations(occ);
                            });
                    })).Start();
            }
            catch { }
        }
        List<Score> Scores;
        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (!App.ViewModel.IsDataLoaded)
            {
                App.ViewModel.LoadData();
            }

            
            
            Scores = Scoreboard.LoadScores();
            //Scores.Add(new Score() { time = "00:00:00", tests = 100, score = 100000, name = "Francesco" });
            App.ViewModel.Scores.Clear();
            App.ViewModel.Scores.Add(new ScoresViewModel() { Time = Strings.Time, Tests = Strings.Tests, Score = Strings.Score, Name = Strings.Name, Index = Strings.Rank });
            for (int i = 0; i < Scores.Count; i++)
            {
                var s = Scores[i];
                App.ViewModel.Scores.Add(new ScoresViewModel()
                {
                    Index = "" + (i + 1),
                    Name = s.name,
                    Score = "" + s.score,
                    Tests = "" + s.tests,
                    Time = s.time
                });
            }
        }
        private void OpenCredits_Button_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/CreditsPage.xaml", UriKind.Relative));
        }
        private void ClearScore_Button_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show(Strings.AreYouSureToClear, Strings.ClearScore, MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            {
                Scoreboard.DeleteScores();
                App.ViewModel.Scores.Clear();
            }
        }
        #region ADS



        public static bool showProducts = false;



        private void Ads_List_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (Ads_List.SelectedItem == null)
                return;
            AdsViewModel ads = Ads_List.SelectedItem as AdsViewModel;
            Ads_List.SelectedItem = null;
            if (ads.Name != Strings.OtherProducts && ads.ID != "")
                OpenMarket(ads.ID);


        }


        private void Ads1_Button_Click(object sender, RoutedEventArgs e)
        {
            PivotControl.SelectedItem = AdsPivot_Name;
        }

        private void OpenMarket(string ID)
        {

            MarketplaceDetailTask marketplaceDetailTask = new MarketplaceDetailTask();
            marketplaceDetailTask.ContentIdentifier = ID;
            marketplaceDetailTask.Show();
        }
        #endregion

        private void GameType_List_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (GameType_List.SelectedItem == null)
                return;
            var item = GameType_List.SelectedItem as GameTypeViewModel;
            var s = item.Name;
            if (s == Strings.Easy)
            {
                NewGamePage.difficulty = GameDifficulty.Easy;
            }
            else if (s == Strings.Normal)
            {
                NewGamePage.difficulty = GameDifficulty.Normal;
            }
            else if (s == Strings.Hard)
            {
                NewGamePage.difficulty = GameDifficulty.Hard;
            }
            else if (s == Strings.Reverse)
            {
                NewGamePage.difficulty = GameDifficulty.Reverse;
            }
            else if (s == Strings.Alpha)
            {
                NewGamePage.difficulty = GameDifficulty.Alpha;
            }
            NewGamePage.start_new_game = true;
            GameType_List.SelectedItem = null;
            NavigationService.Navigate(new Uri("/NewGamePage.xaml", UriKind.Relative));
        }



        private void Global_Ranking_Button_Click(object sender, RoutedEventArgs e)
        {
            WebBrowserTask browser = new WebBrowserTask();
            browser.URL = "http://fboscari.altervista.org/RGBFinderPlus_Scores.php";
            browser.Show();
        }

        private void PivotControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (PivotControl.SelectedItem == ScoresPivot_Name)
            {
                if (Global_Ranking == "")
                    Global_Ranking_Button.Content = Strings.GlobalRank;
                else
                    Global_Ranking_Button.Content = Strings.GlobalRank + ": " + Global_Ranking;
            }
        }



        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            if (showProducts)
            {
                showProducts = false;
                Ads1_Button_Click(null, null);
            }
            if (showScores)
            {
                showScores = false;
                PivotControl.SelectedItem = ScoresPivot_Name;
            }
        }
    }


    public class GameStatus
    {
        public Color secret_color;
        public Color current_color;
        public int tests;
        public GameDifficulty difficulty;
        public long timeSpan_Ticks;
        public int helps = 0;
        public bool enableTimer;
        [XmlIgnore]
        public TimeSpan timer
        {
            get
            {
                return new TimeSpan(timeSpan_Ticks);
            }
            set
            {
                timeSpan_Ticks = value.Ticks;
            }
        }
        public GameStatus()
        {
            secret_color = new Color();
            current_color = new Color();
            tests = 0;
            timeSpan_Ticks = 0;
            difficulty = GameDifficulty.Normal;
            enableTimer = false;
        }
    }
}